package com.epoint.excleutil;

import com.epoint.excleutil.Vo.ExportParams;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;

import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wangchao on 2017/11/15.
 */
public class ExcelStreamUtil {

    public static final String ORIGIN_EXCEL_NAME = "ORIGIN_EXCEL_NAME";
    public static final String EXCEL_STREAM = "EXCEL_STREAM";

    public static Map<String, Object> mapExcelStream(Map<String, Object> model)
            throws Exception
    {
        String codedFileName = "临时文件";
        ExportParams exportParams = (ExportParams)model.get("params");
        Object entity = model.get("EntityList");
        Workbook workbook = null;
        if (entity instanceof List) {
            workbook = ExcelExportUtil.exportExcel(exportParams, (List)model.get("EntityList"), (Collection)model.get("mapList"));
        }
        else
        {
            workbook = ExcelExportUtil.exportExcel(exportParams, (Class)entity, (Collection)model.get("mapList"));
        }

        if (!StringUtils.isEmpty(exportParams.getSheetName())) {
            codedFileName = exportParams.getSheetName();
        }
        if (workbook instanceof HSSFWorkbook)
            codedFileName = codedFileName + ".xls";
        else {
            codedFileName = codedFileName + ".xlsx";
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        workbook.write(out);
        Map map = new HashMap();
        map.put("ORIGIN_EXCEL_NAME", codedFileName);
        map.put("EXCEL_STREAM", out);
        return map;
    }
}
